package com.yys.apm.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 签名工具类
 *
 * @author Yingsheng Ye
 * @date 2021-03-20 18:33
 */
public class SignUtil {

    /**
     * 签名工具
     *
     * @param data    Map
     * @param signKey 秘钥
     * @return String
     */
    public static String sign(Map<String, Object> data, String signKey) {
        List<String> keys = new ArrayList<>(data.keySet());
        Collections.sort(keys);
        StringBuilder content = new StringBuilder();
        content.append(signKey);
        for (String key : keys) {
            Object value = data.get(key);
            content.append(value);
        }
        String result = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(content.toString().getBytes());
            byte[] b = md.digest();
            int i;
            StringBuilder buf = new StringBuilder();
            for (byte value : b) {
                i = value;
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }
}
